// 文件路径: src/main/java/com/macro/mall/tiny/modules/pms/service/impl/ProductSkuServiceImpl.java
package com.macro.mall.tiny.modules.pms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.macro.mall.tiny.modules.pms.dto.ProductSkuAttrValueParam;
import com.macro.mall.tiny.modules.pms.dto.ProductSkuParam;
import com.macro.mall.tiny.modules.pms.dto.ProductSkuQueryParam;
import com.macro.mall.tiny.modules.pms.dto.ProductSkuResponse;
import com.macro.mall.tiny.modules.pms.mapper.ProductSkuMapper;
import com.macro.mall.tiny.modules.pms.model.ProductSku;
import com.macro.mall.tiny.modules.pms.model.ProductSkuAttrValue;
import com.macro.mall.tiny.modules.pms.service.ProductSkuAttrValueService;
import com.macro.mall.tiny.modules.pms.service.ProductSkuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, ProductSku> implements ProductSkuService {

    @Autowired
    private ProductSkuAttrValueService productSkuAttrValueService;

    @Override
    public Page<ProductSku> list(ProductSkuQueryParam queryParam, Integer pageSize, Integer pageNum) {
        Page<ProductSku> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ProductSku> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductSku::getDelFlag, 0);

        // 关键字查询
        if (queryParam != null && StringUtils.hasText(queryParam.getKeyword())) {
            wrapper.and(w -> w.like(ProductSku::getTitle, queryParam.getKeyword())
                    .or()
                    .like(ProductSku::getSkuCode, queryParam.getKeyword()));
        }

        // SKU ID精确查询
        if (queryParam != null && queryParam.getSkuId() != null && queryParam.getSkuId() != 0) {
            wrapper.eq(ProductSku::getSkuId, queryParam.getSkuId());
        }

        // SKU编码精确查询
        if (queryParam != null && StringUtils.hasText(queryParam.getSkuCode())) {
            wrapper.eq(ProductSku::getSkuCode, queryParam.getSkuCode());
        }

        // 价格区间查询
        if (queryParam != null && queryParam.getMinPrice() != null && queryParam.getMinPrice().compareTo(BigDecimal.ZERO) != 0) {
            wrapper.ge(ProductSku::getPrice, queryParam.getMinPrice());
        }
        if (queryParam != null && queryParam.getMaxPrice() != null && queryParam.getMaxPrice().compareTo(BigDecimal.ZERO) != 0) {
            wrapper.le(ProductSku::getPrice, queryParam.getMaxPrice());
        }

        // 创建时间区间查询
        if (queryParam != null && queryParam.getCreateTimeFrom() != null) {
            wrapper.ge(ProductSku::getCreatedAt, queryParam.getCreateTimeFrom());
        }
        if (queryParam != null && queryParam.getCreateTimeTo() != null) {
            wrapper.le(ProductSku::getCreatedAt, queryParam.getCreateTimeTo());
        }
        wrapper.orderByDesc(ProductSku::getSkuId);
        wrapper.orderByDesc(ProductSku::getSort);
        return page(page, wrapper);
    }

    @Override
    public Page<ProductSku> listWithAttrValue(ProductSkuQueryParam queryParam, Integer pageSize, Integer pageNum) {
        // 这里需要在Mapper中添加自定义SQL来处理关联查询
        // 先创建基础查询条件
        Page<ProductSku> page = new Page<>(pageNum, pageSize);

        // 使用自定义Mapper方法处理复杂的关联查询
        // 实现将在ProductSkuMapper中完成
        return page;
    }


    @Override
    public ProductSku getItem(Long id) {
        LambdaQueryWrapper<ProductSku> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductSku::getSkuId, id)
                .eq(ProductSku::getDelFlag, 0);
        return getOne(wrapper);
    }

    @Override
    public ProductSkuResponse getDetailItem(Long id) {
        // 获取 SKU 基本信息
        ProductSku productSku = getItem(id);
        if (productSku == null) {
            return null;
        }

        // 转换为响应对象
        ProductSkuResponse response = new ProductSkuResponse();
        BeanUtils.copyProperties(productSku, response);

        // 查询并设置属性值列表
        List<ProductSkuAttrValue> attrValues = productSkuAttrValueService.listBySkuId(productSku.getSkuId());
        List<ProductSkuAttrValueParam> attrValueParams = attrValues.stream().map(attrValue -> {
            ProductSkuAttrValueParam param = new ProductSkuAttrValueParam();
            param.setPnValue(attrValue.getPnValue());
            param.setPvValue(attrValue.getPvValue());
            return param;
        }).collect(Collectors.toList());

        response.setAttrValueList(attrValueParams);
        return response;
    }

    @Override
    public boolean create(ProductSkuParam productSkuParam) {
        // 保存SKU基本信息
        ProductSku productSku = new ProductSku();
        BeanUtils.copyProperties(productSkuParam, productSku);

        // 设置默认值
        productSku.setDelFlag(0);
        productSku.setCreatedAt(LocalDateTime.now());
        productSku.setUpdatedAt(LocalDateTime.now());

        boolean result = save(productSku);

        // 保存SKU属性值
        if (result && productSkuParam.getAttrValueList() != null && !productSkuParam.getAttrValueList().isEmpty()) {
            List<ProductSkuAttrValue> attrValueList = convertToAttrValueList(productSkuParam.getAttrValueList());
            result = productSkuAttrValueService.saveBatchBySkuId(productSku.getSkuId(), attrValueList);
        }

        return result;
    }

    @Override
    public boolean update(Long id, ProductSkuParam productSkuParam) {
        // 更新SKU基本信息
        ProductSku productSku = new ProductSku();
        BeanUtils.copyProperties(productSkuParam, productSku);
        productSku.setSkuId(id.intValue());
        productSku.setUpdatedAt(LocalDateTime.now());

        boolean result = updateById(productSku);

        // 更新SKU属性值
        if (result && productSkuParam.getAttrValueList() != null) {
            List<ProductSkuAttrValue> attrValueList = convertToAttrValueList(productSkuParam.getAttrValueList());
            result = productSkuAttrValueService.saveBatchBySkuId(productSku.getSkuId(), attrValueList);
        }

        return result;
    }

    @Override
    public boolean delete(Integer id) {
        ProductSku productSku = new ProductSku();
        productSku.setSkuId(id);
        productSku.setUpdatedAt(LocalDateTime.now());
        productSku.setDelFlag(1);

        // 同时删除关联的属性值
        productSkuAttrValueService.removeBySkuId(id);
        System.out.println(productSku);
        return updateById(productSku);
    }

    /**
     * 将ProductSkuAttrValueParam列表转换为ProductSkuAttrValue列表
     */
    private List<ProductSkuAttrValue> convertToAttrValueList(List<ProductSkuAttrValueParam> paramList) {
        List<ProductSkuAttrValue> attrValueList = new ArrayList<>();
        for (ProductSkuAttrValueParam param : paramList) {
            ProductSkuAttrValue attrValue = new ProductSkuAttrValue();
            attrValue.setPnValue(param.getPnValue());
            attrValue.setPvValue(param.getPvValue());
            attrValueList.add(attrValue);
        }
        return attrValueList;
    }

    public Map<Integer, List<ProductSkuAttrValueParam>> batchGetAttrValues(List<Integer> skuIds) {
        // 使用一批skuid，查询对应的属性和属性值，按照skuId进行分组
        Map<Integer, List<ProductSkuAttrValueParam>> result = new HashMap<>();

        if (skuIds == null || skuIds.isEmpty()) {
            return result;
        }

        // 批量查询所有SKU ID对应的属性值
        LambdaQueryWrapper<ProductSkuAttrValue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ProductSkuAttrValue::getSkuId, skuIds);
        queryWrapper.eq(ProductSkuAttrValue::getDelFlag, 0);

        List<ProductSkuAttrValue> attrValues = productSkuAttrValueService.list(queryWrapper);

        // 按照skuId进行分组并转换为ProductSkuAttrValueParam
        return attrValues.stream()
                .collect(Collectors.groupingBy(
                        ProductSkuAttrValue::getSkuId,
                        Collectors.mapping(attrValue -> {
                            ProductSkuAttrValueParam param = new ProductSkuAttrValueParam();
                            param.setPnValue(attrValue.getPnValue());
                            param.setPvValue(attrValue.getPvValue());
                            return param;
                        }, Collectors.toList())
                ));
    }

}
